﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using cludg.Domain.Content;
using cludg.Domain.Content.Stories;
using cludg.Domain.Environment;
using cludg.Services.Content;
using cludg.Web.Core.Controllers;
using cludg.Web.Core.ViewModels;
using cludg.Web.Core.Security;
using cludg.Infrastructure.Core.Attributes;
using cludg.Web.ViewModels;

namespace cludg.Web.Controllers
{
	[HandleError]
	public class HomeController : BaseController
	{
		protected const int PageLength = 5;

		[Dependency]
		public IStoryService StoryService { get; set; }
		[Dependency]
		public ITagService TagService { get; set; }

		[PermissionRequierd("ViewStories")]
		public ActionResult Index(string tag, int page = 1)
		{
			var model = CreateModel<StoryListModel>();
			if (model != null)
			{
				model.NavigationMenu.SetActiveItem("Index");

				IQueryable<Domain.Content.Stories.Story> filteredByTagStories;
				if (!string.IsNullOrWhiteSpace(tag))
				{
					filteredByTagStories = (from story in StoryService.All
											from storyTag in story.Tags
											where storyTag.Name == tag
											select story);
					model.Tag = tag;
				}
				else
				{
					filteredByTagStories = StoryService.All;
				}

				int storyCount = filteredByTagStories.Count();

				int pageCount = storyCount / PageLength;
				if (storyCount % PageLength > 0)
					pageCount++;

				page--;

				if (page > pageCount)
					return RedirectToAction("Index", new { page = pageCount });
				if (page < 0)
					return RedirectToAction("Index");

				model.Stories = filteredByTagStories
					.OrderByDescending(x => x.CreationTime)
					.Skip(page * PageLength)
					.Take(PageLength).ToList();
				// Инициализируем кол-во показов каждой записи, которую будем выводить в списке, из истории показов
				(model.Stories as List<Story>).ForEach(
					x => x.ViewCount = HistoryService.All.Where(y => y.ObjectId == x.Id && y.Type == HistoryEntryType.View).Count()
					);
				model.PageCount = pageCount;
				model.PageNumber = page;
			}

			return View(model);
		}

		public ActionResult About()
		{
			var model = CreateModel<BaseModel>();
			model.NavigationMenu.SetActiveItem("About");
			return View(model);
		}

		public ActionResult TagCloud()
		{
			int totalPosts = StoryService.All.Count();
			var tagCounts = TagService.GetTagContentCount();

			var model = tagCounts.Select(
				tagCount => new TagCountModel
				            	{
				            		Tag = tagCount.TagName,
									TagCount = tagCount.Count,
									TotalPosts = totalPosts
				            	}).ToList();

			return PartialView("TagCloud", model);
		}
	}
}
